/**
 * 教师相关路由
 */

const express = require('express');
const router = express.Router();
const { db } = require('../db');
const { authenticateToken } = require('./auth');

// 中间件：检查是否有权限访问教师信息
const checkTeacherAccess = (req, res, next) => {
  const { role, teacher_id } = req.user;
  const requestedTeacherId = parseInt(req.params.id);

  // 管理员可以访问所有教师信息
  if (role === 'admin') {
    return next();
  }

  // 教师只能访问自己的信息
  if (role === 'teacher' && teacher_id === requestedTeacherId) {
    return next();
  }

  // 学生可以查看自己所选课程的教师信息
  if (role === 'student') {
    db.get(
      `SELECT 1 FROM enrollments e
       JOIN courses c ON e.course_id = c.id
       WHERE e.student_id = ? AND c.teacher_id = ?`,
      [req.user.student_id, requestedTeacherId],
      (err, result) => {
        if (err) {
          return res.status(500).json({ error: '数据库查询错误' });
        }
        if (result) {
          return next();
        }
        res.status(403).json({ error: '无权访问该教师信息' });
      }
    );
    return;
  }

  res.status(403).json({ error: '无权访问该教师信息' });
};

// 获取教师列表
router.get('/', authenticateToken, (req, res) => {
  let query = `
    SELECT 
      t.id, t.teacher_id, t.name, t.gender, 
      t.title, t.department
    FROM teachers t
  `;

  // 如果是学生，只返回与学生相关的教师
  if (req.user.role === 'student') {
    query = `
      SELECT DISTINCT
        t.id, t.teacher_id, t.name, t.gender, 
        t.title, t.department
      FROM teachers t
      JOIN courses c ON t.id = c.teacher_id
      JOIN enrollments e ON c.id = e.course_id
      WHERE e.student_id = ?
    `;
  }

  const params = req.user.role === 'student' ? [req.user.student_id] : [];

  db.all(query, params, (err, teachers) => {
    if (err) {
      return res.status(500).json({ error: '获取教师列表失败', details: err.message });
    }
    res.json({ teachers });
  });
});

// 获取单个教师信息
router.get('/:id', authenticateToken, checkTeacherAccess, (req, res) => {
  db.get(
    `SELECT 
      t.id, t.teacher_id, t.name, t.gender, 
      t.title, t.department,
      u.username, u.created_at
    FROM teachers t
    JOIN users u ON t.user_id = u.id
    WHERE t.id = ?`,
    [req.params.id],
    (err, teacher) => {
      if (err) {
        return res.status(500).json({ error: '获取教师信息失败', details: err.message });
      }
      if (!teacher) {
        return res.status(404).json({ error: '教师不存在' });
      }
      res.json({ teacher });
    }
  );
});

// 更新教师信息（仅管理员和教师本人）
router.put('/:id', authenticateToken, checkTeacherAccess, (req, res) => {
  const { name, gender, title, department } = req.body;
  const teacherId = req.params.id;

  // 只有管理员和教师本人可以更新信息
  if (req.user.role !== 'admin' && req.user.teacher_id !== parseInt(teacherId)) {
    return res.status(403).json({ error: '无权更新该教师信息' });
  }

  db.run(
    `UPDATE teachers 
     SET name = ?, gender = ?, title = ?, department = ?
     WHERE id = ?`,
    [name, gender, title, department, teacherId],
    function(err) {
      if (err) {
        return res.status(500).json({ error: '更新教师信息失败', details: err.message });
      }
      if (this.changes === 0) {
        return res.status(404).json({ error: '教师不存在' });
      }
      res.json({ message: '教师信息更新成功' });
    }
  );
});

// 获取教师的课程列表
router.get('/:id/courses', authenticateToken, checkTeacherAccess, (req, res) => {
  const semester = req.query.semester || '2023-2024-1'; // 默认当前学期

  db.all(
    `SELECT 
      c.id, c.course_id, c.name, c.credit, c.hours,
      c.description, c.max_students, c.semester, c.status,
      (SELECT COUNT(*) FROM enrollments WHERE course_id = c.id) as enrolled_count
    FROM courses c
    WHERE c.teacher_id = ? AND c.semester = ?
    ORDER BY c.course_id`,
    [req.params.id, semester],
    (err, courses) => {
      if (err) {
        return res.status(500).json({ error: '获取课程列表失败', details: err.message });
      }
      res.json({ courses });
    }
  );
});

// 获取教师的课程表
router.get('/:id/schedule', authenticateToken, checkTeacherAccess, (req, res) => {
  const semester = req.query.semester || '2023-2024-1'; // 默认当前学期

  db.all(
    `SELECT 
      c.id as course_id, c.course_id as course_number, c.name as course_name,
      cs.day_of_week, cs.start_time, cs.end_time, cs.classroom
    FROM courses c
    JOIN course_schedules cs ON c.id = cs.course_id
    WHERE c.teacher_id = ? AND c.semester = ?
    ORDER BY cs.day_of_week, cs.start_time`,
    [req.params.id, semester],
    (err, schedule) => {
      if (err) {
        return res.status(500).json({ error: '获取课程表失败', details: err.message });
      }
      res.json({ schedule });
    }
  );
});

// 获取某门课程的学生列表
router.get('/:id/courses/:courseId/students', authenticateToken, checkTeacherAccess, (req, res) => {
  db.all(
    `SELECT 
      s.id, s.student_id, s.name, s.gender, s.class,
      e.enrollment_date, e.grade, e.status
    FROM enrollments e
    JOIN students s ON e.student_id = s.id
    JOIN courses c ON e.course_id = c.id
    WHERE c.id = ? AND c.teacher_id = ?
    ORDER BY s.student_id`,
    [req.params.courseId, req.params.id],
    (err, students) => {
      if (err) {
        return res.status(500).json({ error: '获取学生列表失败', details: err.message });
      }
      res.json({ students });
    }
  );
});

// 录入/更新学生成绩
router.put('/:id/courses/:courseId/grades', authenticateToken, checkTeacherAccess, (req, res) => {
  const { grades } = req.body; // 格式：[{student_id, grade}]
  const { id: teacherId, courseId } = req.params;

  // 验证是否为该课程的教师
  db.get(
    'SELECT 1 FROM courses WHERE id = ? AND teacher_id = ?',
    [courseId, teacherId],
    (err, course) => {
      if (err) {
        return res.status(500).json({ error: '数据库查询错误' });
      }
      if (!course) {
        return res.status(403).json({ error: '无权录入该课程成绩' });
      }

      // 开始事务
      db.serialize(() => {
        db.run('BEGIN TRANSACTION');

        let success = true;
        let processed = 0;

        grades.forEach(({ student_id, grade }) => {
          db.run(
            'UPDATE enrollments SET grade = ? WHERE student_id = ? AND course_id = ?',
            [grade, student_id, courseId],
            function(err) {
              processed++;
              if (err) {
                success = false;
                console.error('更新成绩失败:', err);
              }

              // 当所有更新都完成时
              if (processed === grades.length) {
                if (success) {
                  db.run('COMMIT', (err) => {
                    if (err) {
                      console.error('提交事务失败:', err);
                      return res.status(500).json({ error: '保存成绩失败' });
                    }
                    res.json({ message: '成绩录入成功' });
                  });
                } else {
                  db.run('ROLLBACK', (err) => {
                    if (err) {
                      console.error('回滚事务失败:', err);
                    }
                    res.status(500).json({ error: '部分或全部成绩录入失败' });
                  });
                }
              }
            }
          );
        });
      });
    }
  );
});

module.exports = router;
